﻿using System;
using System.Linq;
using Microsoft.Xna.Framework;

namespace Babylon.Toolbox
{
    public partial class SceneObject : SceneReference
    {
        public event EventHandler<ConfigureEffectArgs> OnConfigureEffect;

        public Model Model { get; set; }
        public int VerticesCount { get; private set; }

        public bool IsVisible { get; set; }

        bool _needAlphaBlending;
        public bool NeedAlphaBlending
        {
            get { return _needAlphaBlending; }
            set
            {
                if (_needAlphaBlending == value)
                    return;
                _needAlphaBlending = value;
                RaisePropertyChanged(()=>NeedAlphaBlending);
            }
        }

        public BoundingSphere BoundingSphere
        {
            get
            {
                if (Model == null)
                    throw new NullReferenceException(Strings.ModelMustBesSet);

                return Model.BoundingSphere;
            }
            set
            {
                if (Model == null)
                    throw new NullReferenceException(Strings.ModelMustBesSet);
                
                Model.BoundingSphere = value;
            }
        }


        public SceneObject(string name, Guid id)
            : base(name, id)
        {
            IsVisible = true;
        }

        public SceneObject(string name)
            : this(name, Guid.NewGuid())
        {
        }

        internal void Draw(Scene rootScene)
        {
            if (Model == null)
                throw new NullReferenceException(Strings.ModelMustBesSet);

            VerticesCount = Model.Meshes.Sum(v => v.VerticesCount);

            foreach (ModelMesh mesh in Model.Meshes)
            {
                foreach (ModelEffect effect in mesh.Effects)
                {
                    effect.World = World;
                    effect.View = rootScene.Camera.View;
                    effect.Projection = rootScene.Camera.Projection;

                    if (OnConfigureEffect != null)
                    {
                        OnConfigureEffect(this, new ConfigureEffectArgs {Effect = effect, ModelMesh = mesh, Scene = rootScene, SceneObject = this});
                    }
                }
            }

            Model.Draw();
        }
    }
}
